/**
 * Canvas 渲染器 - 简化版
 * 直接接收数据并渲染，不依赖复杂的状态管理
 */

import { useEffect, useRef } from 'react'
import type { PluginComponentProps } from '../../types'
import { ScheduleEvents } from '../../types'
import { CanvasDrawer } from './CanvasDrawer'
import { EventHandler } from './EventHandler'
import type { CanvasConfig, ViewPort } from './types'
import './styles.css'

const DEFAULT_CONFIG: CanvasConfig = {
  headerHeight: 60,
  departmentColumnWidth: 120, // 部门列宽度（类似甘特图床型列）
  employeeColumnWidth: 120,
  cellWidth: 120,
  cellHeight: 60,
  backgroundColor: '#ffffff',
  gridColor: '#e0e0e0',
  headerBackgroundColor: '#3498db',
  employeeBackgroundColor: '#f5f5f5',
  textColor: '#333333',
  shiftColors: {
    morning: '#3498db',
    afternoon: '#2ecc71',
    night: '#9b59b6',
    custom: '#f39c12',
  },
  fontSize: 14,
  fontFamily: 'Arial, sans-serif',
  scrollbarSize: 12,
  scrollbarColor: '#cccccc',
  scrollbarHoverColor: '#999999',
}

export function CanvasRenderer({ context }: PluginComponentProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const drawerRef = useRef<CanvasDrawer | null>(null)
  const eventHandlerRef = useRef<EventHandler | null>(null)
  const viewportRef = useRef<ViewPort>({
    scrollX: 0,
    scrollY: 0,
    visibleStartRow: 0,
    visibleEndRow: 0,
    visibleStartCol: 0,
    visibleEndCol: 0,
  })

  // 生成日期列表
  const generateDates = (): string[] => {
    const dates: string[] = []
    const today = new Date()

    for (let i = 0; i < 31; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() + i)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      dates.push(`${year}-${month}-${day}`)
    }

    return dates
  }

  useEffect(() => {
    const canvas = canvasRef.current
    const container = containerRef.current
    if (!canvas || !container) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // ⚠️ 先销毁旧的事件处理器，防止事件监听器堆积
    if (eventHandlerRef.current) {
      console.log('🧹 清理旧的 EventHandler')
      eventHandlerRef.current.destroy()
      eventHandlerRef.current = null
    }

    // 获取所有数据
    const employees = context.getEmployees()
    const shifts = context.getShifts() // 直接获取所有班次
    const dates = generateDates()

    console.log('✨ Canvas 渲染器启动:', {
      员工数: employees.length,
      总班次数: shifts.length,
      日期数: dates.length,
      日期范围: `${dates[0]} ~ ${dates[dates.length - 1]}`,
    })

    // 设置 Canvas 尺寸
    const resizeCanvas = () => {
      const rect = container.getBoundingClientRect()
      const dpr = window.devicePixelRatio || 1

      canvas.width = rect.width * dpr
      canvas.height = rect.height * dpr
      canvas.style.width = `${rect.width}px`
      canvas.style.height = `${rect.height}px`

      ctx.scale(dpr, dpr)

      if (drawerRef.current) {
        drawerRef.current.draw()
      }
    }

    resizeCanvas()
    window.addEventListener('resize', resizeCanvas)

    // 创建绘制器
    drawerRef.current = new CanvasDrawer(
      canvas,
      ctx,
      DEFAULT_CONFIG,
      employees,
      dates,
      shifts,
      viewportRef.current
    )

    // 创建事件处理器（确保只有一个实例）
    console.log('✨ 创建新的 EventHandler')
    eventHandlerRef.current = new EventHandler(
      canvas,
      drawerRef.current,
      context,
      employees,
      dates,
      shifts
    )

    // 首次绘制
    drawerRef.current.draw()

    // 监听数据变化事件，重新获取数据并重绘
    const handleDataChange = () => {
      if (!drawerRef.current || !eventHandlerRef.current) return

      const newEmployees = context.getEmployees()
      const newShifts = context.getShifts()
      const newDates = generateDates()

      console.log('🔄 数据变化，重新绘制 Canvas:', {
        员工数: newEmployees.length,
        班次数: newShifts.length,
      })

      // 更新 Drawer 的数据
      drawerRef.current = new CanvasDrawer(
        canvas,
        ctx,
        DEFAULT_CONFIG,
        newEmployees,
        newDates,
        newShifts,
        viewportRef.current
      )

      // 更新 EventHandler 的数据
      eventHandlerRef.current.updateData(newEmployees, newDates, newShifts)

      // 重新绘制
      drawerRef.current.draw()
    }

    // 监听所有数据变化事件
    const unsubscribers = [
      context.on(ScheduleEvents.SHIFT_ADDED, handleDataChange),
      context.on(ScheduleEvents.SHIFT_UPDATED, handleDataChange),
      context.on(ScheduleEvents.SHIFT_REMOVED, handleDataChange),
      context.on(ScheduleEvents.EMPLOYEE_ADDED, handleDataChange),
      context.on(ScheduleEvents.EMPLOYEE_UPDATED, handleDataChange),
      context.on(ScheduleEvents.EMPLOYEE_REMOVED, handleDataChange),
    ]

    return () => {
      window.removeEventListener('resize', resizeCanvas)
      eventHandlerRef.current?.destroy()
      unsubscribers.forEach(unsub => unsub())
    }
  }, [context])

  return (
    <div className="canvas-renderer-container" ref={containerRef} style={{ position: 'relative' }}>
      <canvas ref={canvasRef} className="canvas-renderer" />
    </div>
  )
}
